package com.fun.demo;

import java.io.*;
import java.nio.charset.Charset;
import java.util.Enumeration;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

/**
 * 基础的zip & unzip 。
 * */
public class ZIpTest {

    static String zipDir="F:/zz2ZipFile/";
    static String unzipDir="F:/zzUnzipFile/";
    static String[] files = { "1.txt",  "2.txt",  "3.txt"};

    public static void main(String[] args) throws IOException {
//        String destFileName = "F:/" + UUID.randomUUID() + ".zip";
//        FileOutputStream fos = new FileOutputStream(destFileName);
//        zip(fos, files);
//        System.out.println("zip OK : " + destFileName);

        String destFileName = "F:/zzUnzipFile/V9demo姓名.zip";
        unzip(destFileName);
        System.out.println("unzip OK : " + destFileName);
    }

    public static byte[] readFile(String fileName) throws IOException {
        FileInputStream fis = new FileInputStream(fileName);
        byte[] data = new byte[fis.available()];
        fis.read(data);
        return data;
    }

    public static  void unzip(String zipFileName){
        try {
            //解决中文名称解压报错,windows默认编码GBK,ZopFile默认编码UTF-8导致
            Charset charset = Charset.forName("GBK");
            ZipFile zipFile = new ZipFile(zipFileName, charset);
            Enumeration<ZipEntry> entries = (Enumeration<ZipEntry>) zipFile.entries();
            while (entries.hasMoreElements()){
                ZipEntry zipEntry = entries.nextElement();
                File file = new File(unzipDir + zipEntry.getName());
                if(!file.exists()){
                    file.createNewFile();
                }
                FileOutputStream fileOutputStream = new FileOutputStream(file);
                InputStream is = zipFile.getInputStream(zipEntry);
                byte[] data = new byte[1024];
                int k = 0;
                while((k = is.read(data)) != -1){
                    fileOutputStream.write(data, 0, k);
                }

                //finally
                fileOutputStream.close();
                is.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void zip(OutputStream os, String[] fileNames){
        ZipOutputStream zipOutputStream = new ZipOutputStream(os);
        for (String filaName : fileNames) {
            ZipEntry z = new ZipEntry(filaName);
            try {
                zipOutputStream.putNextEntry(z);
                zipOutputStream.write(readFile(zipDir + filaName));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            zipOutputStream.closeEntry();
            zipOutputStream.close();

            //finally
            os.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
